<?php
namespace Home\Controller;

use data\Service\cart\ShopCart as CartService;
use data\Service\shop\Address as AddressService;
use data\Service\pay\PayMent as PayMentService;
use data\Service\goods\Product as GoodsService;
use data\Service\BaseService as BaseService;
use Think\Controller;
use Home\Aip\Store;
use Home\Controller\CommonController;
use Home\Controller\AlipayController;
use Home\Controller\MemberController;
 
class SpBuyController extends CommonController {
	protected $tb_store = 'store';//店铺表	
	protected $tb_goods = 'product';//产品数据表
	protected $tb_cart = 'shop_cart';//购物车表
	protected $tb_address = 'address';//收货地址表
	protected $tb_order_pay = 'order_pay' ;//订单支付表
	protected $tb_order	= 'order' ;//订单支付表
	protected $tb_order_g = 'order_goods' ;//订单产品表
	protected $tb_pay = 'payment' ;//支付方式表
	protected $tb_user = 'user' ;//会员表
	protected $tb_money = 'integral' ;//会员钱包表
	
	protected $spcart = null;
	protected $address = null;
	protected $payment = null;
	private $goods = null;
	private $Base = null;

	/*
	*取消订单
	*
	*/
	public function clear_order() {
		if (I('post.act')=="member_order" && I('post.op')=="change_state" && I('post.state_type')=="order_cancel" && I('post.order_id') && I('post.rec_id')) {
			unset($str);
			unset($arr);
			$str = "rec_id=%d";
			$arr = array(I('post.rec_id'));				
			$order = _getOne($this->tb_order_g, $str, $arr) ;
			
			if (!$order) {
				$this->ajaxReturn("订单不存在！");
			}
			
			if ($order['order_state']>10) {
				$this->ajaxReturn("订单已付款，不能取消！");
			}
					
			$del_f = _getDel($this->tb_order_g, $str, $arr) ;
			
		if ($del_f) {
			unset($str);
			unset($arr);
			$str = "order_id=%d";
			$arr = array(I('post.order_id'));			
			$order_goods = _getOne($this->tb_order_g, $str, $arr) ;
			
			$order_max = _getOne($this->tb_order, $str, $arr) ;
			
			if ($order_goods) {
				//修改金额
				unset($data);
				$data ['order_amount']= $order_max ['order_amount'] - $order['goods_price'] * $order['goods_num'];
				$order_goods = _getEdit($this->tb_order, $str, $arr, $data) ;
				
				$this->ajaxReturn("取消订单成功！");	
			}
			
			
			unset($str);
			unset($arr);
			$str = "pay_sn='%s'";
			$arr = array($order_max['pay_sn']) ;
			$del = _getDel($this->tb_order_pay, $str, $arr) ;

			unset($str);
			unset($arr);
			$str = "order_id=%d";
			$arr = array(I('post.order_id')) ;
			$del2 = _getDel($this->tb_order, $str, $arr) ;
			if ($del2) {	
				$this->ajaxReturn("取消订单成功！");				
			} else {
				$this->ajaxReturn("取消订单失败！");
			}
		} else {
			$this->ajaxReturn("订单不存在！");
		}	
	  } else {
			$this->ajaxReturn("非法操作！");
	  }	
	}


	/**
	*立即购买
	*/
	public function shop_buy_1() {
		
		if (I('post.type')=='buy' && I('post.goods_id')) {
			$this->ajaxReturn(array('error'=>1));
			if ($_SESSION['user_id'] && session('boboid')==session('user_id')) {
 				//会员登录状态
				$this->buy_order_1();				
			} else {
				 $this->ajaxReturn(array('error'=>1));
			}				
		} else {
			 $this->ajaxReturn(array('error'=>1));
		}
	}
	
	/**
	*确认订单
	*/
	public function buy_order_1() {
		
		if (IS_POST || $_SESSION['order_post']) {
			
			if (!$_SESSION['order_post']) {
				session('order_post',I('post.'));
			}

			unset($str);
			unset($arr);
			unset($order);
			unset($result);
			$str = 'id>%d and userid=%d';
			$arr = array(0,$_SESSION['user_id']);
			$order = 'id desc';
			//删除缓存
			session('pay_sn_number',null) ;
			session('pay_sn_number_2',null) ;
			session('cart_list'.$_SESSION['user_id'],null) ;
			
			$get_address = _getList($this->tb_address, $str, $arr, '', $order);
			$get_address && $addss_state = 1 ;
			
			$c_list = '' ;
			$c_arr = '' ;
			//购物车内的产品
			I('post.cart_id')?$cart_id = I('post.cart_id') : $cart_id =$_SESSION['order_post']['cart_id'] ;
			
			foreach ($cart_id as $key=>$v) {
				unset($car_arr);
				$car_arr = explode('|',$v) ;
				$c_name ['goods_id'] = $car_arr[0] ;
				$c_name ['goods_num'] = $car_arr[1] ;
				$c_name ['cart_id'] = $car_arr[2] ;
				if (!$c_list) {
					$c_list .= '(buyer_id=%d and c.goods_id=%d and c.goods_num=%d and c.cart_id=%d) ';
					$c_arr .= $_SESSION ['user_id'].','.$car_arr[0].','.$car_arr[1].','.$car_arr[2] ;
				} else {
					$c_list .= 'or (buyer_id=%d and c.goods_id=%d and c.goods_num=%d and c.cart_id=%d) ' ;
					$c_arr .= ','.$_SESSION ['user_id'].','.$car_arr[0].','.$car_arr[1].','.$car_arr[2] ;
				}	
			}
			
			//购物车产品信息			
			$this->spcart = new CartService();
			
			$c_arr && $result = $this->spcart->goodsCartInfo($c_list, $c_arr);
							
			//立即购买产品
			
			I('post.goods_id')?$goods_id = I('post.goods_id') : $goods_id = $_SESSION['order_post']['goods_id'] ;
			I('post.goods_nums')?$goods_nums = I('post.goods_nums') : $goods_nums = $_SESSION['order_post']['goods_nums'] ;
				
			if (!$result && I('post.goods_id') && $goods_nums>0) {				
				$result = $this->spcart->atBuyGoodsInfo($goods_id,$goods_nums,I('post.'));
				
				if ($result===4) {					
					die('<script>alert("库存不足");history.back(-1);</script>') ;
				}else{
					session('cart_list'.$_SESSION['user_id'],$result);
				} 
			}
			if (!$result["cart_st"][0]["store_id"]) {
				$this->redirect('/shop/index');	
			}
			//支付方式
			$pay_code = _getOne($this->tb_pay, 'payment_id=%d', array($result['pay_id'])) ;
			
			$this->assign('allcoins',$result['allcoins']);
			$this->assign('amount_coin',$result['amount_coin']);	
			$this->assign('allpoints',$result['allpoints']);
			$this->assign('amount_points',$result['amount_points']);
			$this->assign('goods_freight',$result['goods_freight']);
			$this->assign('total',$result['total']);
			$this->assign('alltotal',$result['alltotal']);
			$this->assign('cart_list',$result['cart_st']);
			$this->assign('payment_name',$pay_code['payment_name']);
			
			$this->assign('addss_state',$addss_state);
			$this->assign('address',$get_address);

			$this->display();
		} else {
			$this->redirect('/shop/index');			
		}
	}
	
	/**
	*收货地址1
	*/
	public function buy_address_b1() {		
		$this->display();
	}
	
	/**
	*收货地址操作
	*/
	public function add_address_n() {
		if (IS_POST) {
			$adr = new MemberController();
			$result = $adr->add_address();
			if ($result) {
				die("<script>alert('新增成功！');location.href=document.referrer;</script>") ;
			}
		}
		
	}
	
	/**
	*收货地址2
	*/
	public function buy_address_b2() {		
		$this->display();
	}
	
	/**
	*提交订单
	*/
	public function buy_order_2() {
		
		if (IS_POST || I('get.pay_sn')) {
			
			//dump(I('post.'));die;
			if (I('post.act')=='buy' && I('post.op')=='buy_step2') {
				
				$this->buyOrderJoin() ;
				$rees = 1 ;
			} else {
				session('pay_sn_number',null) ;
				session('pay_sn_number_2',null) ;
			}
			session('pay_order_id',null);
			if (I('get.pay_sn') && I('get.act')=="buy" && I('get.op')=="pay") {
				$rees = 1 ;
			} 
			//dump($rees);die;
			if(!$rees) {
				$this->redirect('/shop/index');
			}
			
			 $_SESSION['pay_sn_number'] && $pay_sn = $_SESSION['pay_sn_number'] ;	
			 $_SESSION['pay_sn_number_2'] && $pay_sn = $_SESSION['pay_sn_number_2'] ;			 
			!$pay_sn && $pay_sn = I('get.pay_sn') ;
			unset($str);
			unset($arr);
			$str = '(order_sn="%s" and buyer_id=%d and order_state=%d)' ;
			//dump($pay_sn);die;
			if (is_array($pay_sn)) {
				$i = 0 ;
				$arr = '';
				$str = '' ;
				foreach ($pay_sn as $key=>$v) {					
				
						foreach ($v as $k=>$vv) {
							if (!$str) {
								$str .= '(order_sn="%s" and buyer_id=%d and order_state=%d)' ;
								$arr .= $vv.','.$_SESSION['user_id'].',10' ;
							} else {
								$str .= ' or (order_sn="%s" and buyer_id=%d and order_state=%d)' ;
								$arr .= ','.$vv.','.$_SESSION['user_id'].',10' ;		
							}						
							$spn .= '|'.$vv ;
						}
				}
				$pay_sn = $spn ;				
			} else {
				$str = 'order_sn="%s" and buyer_id=%d and order_state=%d' ;	
				$arr = $pay_sn.','.$_SESSION['user_id'].',10' ;	
			}						
			$arr = explode(',',$arr);

			$order_list = _getList($this->tb_order, $str, $arr) ;
			
					
			!$order_list && $this->redirect('/shop/index');
			
			foreach ($order_list as $key=>$v) {
				//总金额
				$amount += $v['order_amount'] ;
				//总积分
				$points_amount += $v['points_amount'] ;
				//总增值币
				$gold_amount += $v['gold_amount'] ;

				//支付方式
				unset($result);
				$result = shop_pay_type($v,$v);
				$pay_name = $result['pay_name'] ;
				$order_list[$key]['m_html'] = $result['m_html'] ;
				
				$amount_html = '¥'.$amount;
				$points_amount_html = $points_amount.'<font style="font-size:12px;">&nbsp;&nbsp;积分</font>';
				$coin_amount_html = $gold_amount.'<font style="font-size:12px;">&nbsp;&nbsp;币</font>';
				
				if ($amount && $points_amount && !$gold_amount) {
					$m_html = $amount_html.'&nbsp;+&nbsp;'.$points_amount_html ;
				} else if ($amount && !$points_amount && !$gold_amount) {
					$m_html = $amount_html ;
				} else if (!$amount && $points_amount && !$gold_amount) {
					$m_html = $points_amount_html ;
				} else if (!$amount && !$points_amount && !$gold_amount) {
					$m_html = $coin_amount_html ;
				} else if (!$amount && $points_amount && $gold_amount) {
					$m_html = $points_amount_html.'&nbsp;+&nbsp;'.$coin_amount_html ;
				} else if ($amount && !$points_amount && $gold_amount) {
					$m_html = $amount_html.'&nbsp;+&nbsp;'.$coin_amount_html ;
				} else if ($amount && $points_amount && $gold_amount) {
					$m_html = $amount_html.'&nbsp;+&nbsp;'.$points_amount_html.'&nbsp;+&nbsp;'.$coin_amount_html ;
				}
				
				//积分+现金支付
				if ($result['payment_code']==='points_consume') {
					$pay_arr = 1 ;					
				}
				
				//积分支付
				if ($result['payment_code']!=='points') {
					$pay_type = 1 ;					
				} 
				//在线支付 现金支付
				if ($result['payment_code']=='online') {
					$pay_type = 1 ;
				}

				$pay_name = $result['payment_name'] ;
				$pay_mm = $result['payment_code'] ;
			}
				
			session('888zffs',$pay_mm);//支付方式
			
			$pay_list = _getList($this->tb_pay, 'payment_id>%d and payment_state=%d', array(0,1)) ;
			//dump($pay_arr);die;
			$this->assign('pay_name_print',$pay_name_print);
			$this->assign('m_html',$m_html);
			$this->assign('amount',number_format($amount,2));
			$this->assign('order_list',$order_list);
			$this->assign('s_pay',$s_pay);
			$this->assign('pay_type',$pay_type);
			$this->assign('pay_arr',$pay_arr);//
			$this->assign('pay_name',$pay_name);//支付方式
			$this->assign('pay_mm',$pay_mm);//支付方式代码
			$this->assign('pay_sn',$pay_sn);//订单编号
			$this->assign('spn',$spn);//多张订单
			$this->assign('pay_list',$pay_list);//支付方式
			$this->display();
			
		} else {
			$this->display('buy_step1');
		}
		
	}

	/**
	 * 生成订单
	 *
	 */
	 private function buyOrderJoin() {
		 
				$c_list = '';
				$c_arr = '';
				$result = array();
				foreach (I('post.goods_id') as $k=>$gv) {
					$goods_list[] = explode('|',$gv) ;			
				}
				//查询条件
				foreach (I('post.cart_id') as $key=>$v) {
					unset($cart_st);
					$cart_st = explode('|',$v);
					if (!$c_list) {
						
						$c_list .= '(buyer_id=%d and c.cart_id=%d and c.store_id=%d and c.goods_id=%d and c.goods_num=%d) ';
						$c_arr .= $_SESSION ['user_id'].','.$cart_st[0].','.$cart_st[1].','.$goods_list[$key][0].','.$goods_list[$key][1] ;
					} else {
						$c_list .= 'or (buyer_id=%d and c.cart_id=%d and c.store_id=%d and c.goods_id=%d and c.goods_num=%d) ' ;
						$c_arr .=  ','.$_SESSION ['user_id'].','.$cart_st[0].','.$cart_st[1].','.$goods_list[$key][0].','.$goods_list[$key][1] ;
					}	
				}
				
				//购物车产品信息			
				$this->spcart = new CartService();
				
				if ($_SESSION['cart_list'.$_SESSION['user_id']]) {
					//直接购买
					$result = $_SESSION['cart_list'.$_SESSION['user_id']];					
					//buy_goods_list($_SESSION['cart_list'.$_SESSION['user_id']]['goods_id'], $_SESSION['cart_list'.$_SESSION['user_id']]['goods_num']) ;
					
				} else {
					//购物车产品信息
					$c_arr && $result = $this->spcart->goodsCartInfo($c_list, $c_arr);
				}				
					
				if ($result) {
					
					$this->address = new AddressService();
					$this->payment = new PayMentService();
					$this->goods = new GoodsService();
					$this->Base = new BaseService();
					
					//先设定一个值为 true;
					$allAdded = true;
					$order = M($this->tb_order);
					$order->startTrans(); //开启事物
					
					$UserInfo = S('user_'.$_SESSION['user_id']);
					
					//插入订单产order
					
					//收货人地址
					unset($str);
					unset($arr);
					$str = 'id=%d' ;
					$arr = array(I('post.address_id')) ;
					$buy_user = $this->address->getAddressInfo($str, $arr, '*');
					//_getOne($this->tb_address, $str, $arr) ;
					$i = 0 ;
					$j = 0 ;
					$sp = 0 ;
					$n = 0 ;					
						
					foreach ($result["cart_st"] as $kk=>$vv) {
						//同一店铺
						if (!$storeid) {
							$storeid = $vv["store_id"] ;
							$i = $i+1 ;								
						}
						//不同店铺
						if ($storeid!==$vv["store_id"]) {
							$j = $j+1 ;								
						}
						
						$p[$vv["store_id"]] = 0 ;
						
						//判断有几种支付方式					
						foreach ($vv['son_c'] as $key=>$v) {
								
							if (!$g_pay[$vv["store_id"]]) {
								$g_pay[$vv["store_id"]] = $v["pay_id"] ;
								//总金额
								$total[$vv["store_id"]][$v["pay_id"]] += $v['amount'] ;
								//总积分
								$allpoints[$vv["store_id"]][$v["pay_id"]] += $v['amount_points'] ;
								//总增值币
								$allcoins[$vv["store_id"]][$v["pay_id"]] += $v['amount_coin'] ;
								//物流运费
								if ($v['goods_freight']>$goods_freight[$vv["store_id"]][$v["pay_id"]]) {
									$goods_freight[$vv["store_id"]][$v["pay_id"]] = $v['goods_freight'] ;
								}
							}
								
							if ($g_pay[$vv["store_id"]]!=$v["pay_id"]) {
								
								$g_pay[$vv["store_id"]] = $v["pay_id"] ;
								
								//同一店铺 不同支付方式的排序 
								$p[$vv["store_id"]] =  $p[$vv["store_id"]] +1 ;
								//同一店铺需要生产多张订单的标记
								$sp = $sp+1 ;
								//总金额
								$total[$vv["store_id"]][$v["pay_id"]] += $v['amount'] ;
								//总积分
								$allpoints[$vv["store_id"]][$v["pay_id"]] += $v['amount_points'] ;
								//总增值币
								$allcoins[$vv["store_id"]][$v["pay_id"]] += $v['amount_coin'] ;
								//物流运费
								if ($v['goods_freight']>$goods_freight[$vv["store_id"]][$v["pay_id"]]) {
									$goods_freight[$vv["store_id"]][$v["pay_id"]] = $v['goods_freight'] ;
								}
							}
								//支付ID
								$g_pay_id [$p[$vv["store_id"]]] = $v["pay_id"] ;
								//支付方式
								unset($pay_code_2);
								
								$pay_code_2 = $this->payment->getPayInfo('payment_id=%d', array($v["pay_id"]), '*');
								
								//_getOne($this->tb_pay, 'payment_id=%d', array($v["pay_id"])) ;
								$pay['pay_name'][$vv["store_id"]][$p[$vv["store_id"]]] = $pay_code_2 ['payment_code'] ;	
								
							}
							
							//dump($allpoints);die;		
							if ($j>0 && $i>0) {
								//一张订单
								$_SESSION['pay_sn_number'][$vv["store_id"]] = $number ;
								unset($store_id);
							} else {
								//多张订单
								$store_id = $vv["store_id"] ;
							}
							
							$_SESSION['pay_sn_number'][$vv["store_id"]] = array();
							
							for ($n=0;$n<=$p[$vv["store_id"]];$n++) {
									
								//支付编号
								$_SESSION['user_id'] && $pay_sn = makePaySn($_SESSION['user_id']) ;
								//添加订单支付数据
								$state = '10' ;//0默认未支付
								$pay_sn && $pay_id = AddPay_sn($this->tb_order_pay, $pay_sn, $state) ;				
								//订单编号							
								$pay_id && $number = makeOrderSn($pay_id);
								//插入订单数据表
								!$g_pay_id[$n] && $g_pay_id[$n]=0;
																
								if($number) {
									//订单编号
									
									$_SESSION['pay_sn_number'][$vv["store_id"]][] = $number ;
									
									unset($data);
									$data ['store_id'] = $vv["store_id"] ;//店铺ID
									$data ['shipping_fee'] = $result ['goods_freight'][$vv["store_id"]] ;//运费
									$data ['buyer_id'] = $_SESSION['user_id'] ;//会员ID
									
									$data ['buyer_name'] = $UserInfo['realname'] ;//会员姓名
									
									I('post.pay_message')[$vv["store_id"]] && $data ['order_message'] = I('post.pay_message')[$vv["store_id"]] ;//买家留言
									
									$data ['order_sn'] = $number ;//订单编号
									$data ['order_state'] = $state ;//支付状态
									$data ['add_time'] = time() ;//下单时间
									$data ['store_name'] = $vv['store_name'] ;//店铺名称
									//支付方式
									$data ['payment_code'] = $pay['pay_name'][$vv["store_id"]][$n] ; 
									$data ['goods_amount'] = $total[$vv["store_id"]][$g_pay_id[$n]]; // 商品总价
									$data ['order_amount'] = $total[$vv["store_id"]][$g_pay_id[$n]] + ($goods_freight?$goods_freight[$vv["store_id"]][$g_pay_id[$n]]:$data ['shipping_fee']); //订单总金额
									
									$data ['points_amount'] = $allpoints[$vv["store_id"]][$g_pay_id[$n]] ;//积分总数
									$data ['gold_amount'] = $allcoins[$vv["store_id"]][$g_pay_id[$n]] ;//增值币总数

									$data ['pay_sn'] = $pay_sn ;//支付编号
									$data ['realname'] = $buy_user ['realname'] ;//收货人姓名
									$data ['province'] = $buy_user ['province'] ;//省
									$data ['city'] = $buy_user ['city'] ;//市
									$data ['area'] = $buy_user ['area'] ;//区
									$data ['address'] = $buy_user ['address'] ;//详细地址
									$data ['tel_phone'] = $buy_user ['tel_phone'] ;//收货人固话
									$data ['mob_phone'] = $buy_user ['mob_phone'] ;//收货人手机号码	
									
									$add = _addOrder($this->tb_order, $data);
									 if(!$add){
										$order->rollback(); //如果order添加失败事物回滚
										$allAdded = false; //并且把allAdded设置为 false
									 }
									 //回滚
									 if($allAdded){
										$order->commit(); 
										// 如果allAdded为真则两条数据都成功；那么 commit事物提交
										//订单号ID
										$_SESSION['pay_order_id'][$vv["store_id"]][$g_pay_id[$n]] = $add ;
										unset($goods_freight[$vv["store_id"]][$g_pay_id[$n]]);
										unset($total[$vv["store_id"]][$g_pay_id[$n]]);
									 }else{
										return false;
									 }
									
								} else {
									_getDel($this->tb_order_pay, 'pay_sn=%d', array($pay_sn));
								}
							  }
							
						}							
						
						//一张订单						
						if ($store_id && !$sp) {
							session('pay_sn_number_2',null);
							$aaa = strval($_SESSION['pay_sn_number'][$store_id][0]);
							//dump($aaa);die;
							session('pay_sn_number',null);
							session('pay_sn_number_2',$aaa);
						} else {
							session('pay_sn_number_2',null);
						}
				//dump($_SESSION);die;
					//插入订单产品表
					
					if ($add) {

						foreach ($result["cart_st"] as $kk=>$vv) {
							if (!$storeid) {
								$storeid = $vv["store_id"] ;							
							}
							
							foreach ($vv['son_c'] as $key=>$v) {
								unset($data);
									
								$data ['goods_id'] = $v['goods_id'] ;//商品ID
								$data ['goods_image'] = $v ['goods_image'] ;//商品图片
								$data ['goods_name'] = $v['goods_name'] ;//商品名称
								$v['goods_price'] && $data ['goods_price'] = $v['goods_price'] ;//商品单价
								$v['goods_price'] && $data ['goods_pay_price'] = $v['goods_price'] ;//商品实际成交价
								$v['color_n'] && $data ['color_n'] = $v['color_n'] ;//商品颜色
								$v['spec_n'] && $data ['spec_n'] = $v['spec_n'] ;//商品规格
								if (!$v['spec_n'] && !$v['color_n']) {
									$spec = $this->goods->getGoodsSpec($v['colorkey'], $v['speckey'], $v['goods_id']);
									if ($spec) {
										$data ['color_n'] = $spec['color_n'] ;//商品颜色
										$data ['spec_n'] = $spec['spec_n'] ;//商品规格
										$data ['speckey'] = $v['speckey'] ;//颜色ID
										$data ['colorkey'] = $v['colorkey'] ;//颜色ID
									}
								}
								
								//dump($data);die;	

								$data ['goods_num'] = $v['goods_num'] ;//商品数量
								$data ['buyer_id'] = $_SESSION['user_id'] ;//买家ID
								$data ['order_id'] = $_SESSION['pay_order_id'][$vv["store_id"]][$v["pay_id"]] ;//订单id
								$data ['store_id'] = $vv["store_id"] ;//店铺ID
								//添加订单商品
								$v['point_num'] && $data ['point_num'] = $v['point_num'] ;//积分价
								$v['coin_num'] && $data ['coin_num'] = $v['coin_num'] ;//增值币价
								$v['give_coin'] && $data ['give_coin'] = $v['give_coin'] ;//赠送增值币
								
								//支付方式
								unset($pay_code_2);
								$pay_code_2 = $this->payment->getPayInfo('payment_id=%d', array($v["pay_id"]), '*');
								
								$data ['payment_code'] = $pay_code_2['payment_code'] ;
								$add_2 = _addOrder($this->tb_order_g, $data);
											
								//清空会员购物车
								$add_2 && $this->spcart->getCartDel('cart_id=%d', array($v['cart_id']));
								
								//更新购物车
								$add_2 && $this->Base->delCart($v['goods_id']);
									
							}							
						}
						
						if ($add_2) {
							session('cart_list'.$_SESSION['user_id'],null);
							return true;
						} else {
							_getDel($this->tb_order, 'id=%d', array($add));
							_getDel($this->tb_order_pay, 'pay_sn=%d', array($pay_sn));
						}
					} else {
						_getDel($this->tb_order_pay, 'pay_sn=%d', array($pay_sn));
					}					
				}			
	 }	

	/**
	*会员二级密码检测
	*/
	public function pay_password_sn() {	
		if (IS_POST) {
			
			if (I('post.password')) {
				unset($str);
				unset($arr);
				$str = 'id=%d and username="%s"' ;
				$arr = array($_SESSION['user_id'],$_SESSION['user_name']) ;
				$user = _goLogin($this->tb_user, $str, $arr) ;

				if (_checkPwd(MD5(I('post.password')),$user['paypassword'])) {
					$res = 1 ;
				} else {
					$res = 0 ;
				}				
				$this->ajaxReturn($res);
			}
			
		}
	}

	/**
	*支付订单
	*/
	public function order_pay_spet1() {		
		if (IS_POST) {
			session('order_post',null);
			if (!I('post.password_callback') && !I('post.payment_code')) {
				
				die('<script>alert("请选择一种支付方式！");history.back(-1);</script>') ;
			} 			
			
			//判断会员二级密码是否正确
			unset($str);
			unset($arr);
			$str = 'id=%d and username="%s"' ;
			$arr = array($_SESSION['user_id'],$_SESSION['user_name']) ;
			$user = _goLogin($this->tb_user, $str, $arr) ;
			
			if (!_checkPwd(MD5(I('post.password')),$user['paypassword']) && $_SESSION['888zffs']!=='online' && I('post.pd_pay') && I('post.password_callback')) {
				die('<script>alert("支付密码错误！");history.back(-1);</script>') ;
			} 
			
			//判断在线支付方式是否存在
			$pay_code = _getOne($this->tb_pay, 'payment_code="%s" and payment_state=%d', array(I('post.payment_code'), 1)) ;
			if (I('post.payment_code') && !$pay_code) {
				die('<script>alert("支付方式不存在！");history.back(-1);</script>') ;				
			}
					
			//dump($_SESSION['888zffs']);die;
			//判断订单号是否存在 订单是否已支付
			unset($str);
			unset($data);
			unset($join);
			unset($table);
			$str = "order_id=%d";
			$data = array(I('post.order_id'));						
			//订单查询
			$order_list = _getOne($this->tb_order, $str, $data);

			$order_list && $order_list['goods_list'] = _getList($this->tb_order_g, $str, $data);	
			
			foreach ($order_list['goods_list'] as $key => $v) {					
				unset($str);
				unset($arr);
				$str = "id=%d and goods_state=%d and goods_verify=%d" ;
				$arr = array($v['goods_id'],1,1) ;
				$goods_f = _getOne($this->tb_goods, $str, $arr) ;	
							
				if (!$goods_f) {
					die('<script>alert("商品已下架！");history.back(-1);</script>') ;
				}
				//dump($order_list);die;	
			}
						
			if (!$order_list) {
				die('<script>alert("订单不存在！");history.back(-1);</script>') ;
			}
			
			if ($order_list['order_state']!=='10') {
				die('<script>alert("订单已支付，请勿重复支付！");history.back(-1);</script>') ;
			}
			
			//判断金额是否足够
			unset($str);
			unset($data);
			unset($join);
			$str = "id=%d and username='%s'";
			$data = array($_SESSION['user_id'],$_SESSION['user_name']);			
			$join = 'RIGHT JOIN __INTEGRAL__ ON __INTEGRAL__.userid = __USER__.id';				
			//关联查询
			$UserInfo = _getJoinOne($this->tb_user,$join,$str,$data);
			
			//站内支付方式是否存在
			I('post.password_callback') && $pay_code2 = _getOne($this->tb_pay, 'payment_code="%s" and payment_state=%d', array($_SESSION['888zffs'],1)) ;
			
			
			if (!$pay_code2) {
				$pay_code2['payment_code'] = $order_list ['payment_code'] ;
			}
			unset($pay_user);
			unset($pay_money);//在线支付金额
			unset($user_points);//会员积分
			unset($res);
			   //预存款支付
			if ($pay_code2['payment_code']==='consume') {
				
				if (I('post.rcb_pay')) {
					//站内支付金额
					if ($order_list['order_amount']>$UserInfo['member_balance']) {
						$pay_money = $order_list['order_amount'] - $UserInfo['member_balance'];						
					    $paymoney = $UserInfo['member_balance'] ;
					} else {
						$paymoney = $order_list['order_amount'];
					}					

					$res = 1 ;
				} else {
					//线上支付
					$pay_money = $order_list['order_amount'] ;
					//站内支付金额
					$paymoney = 0 ;
				}
				

			} else if ($pay_code2['payment_code']==='points') {
				//纯积分支付
				//积分总和 
				$user_points = $UserInfo ['integral5'] + $UserInfo ['integral1'] + $UserInfo ['integral2'] ;
				if ($user_points<$order_list['points_amount']) {
					die('<script>alert("会员积分数不足，请选择其他支付方式！");history.back(-1);</script>') ;
				}
				$paypoints = $order_list['points_amount'] ;
				$res = 2 ;
				
			} else if ($pay_code2['payment_code']==='points_consume') {
				
				//预存款支付+积分支付
				if (I('post.rcb_pay')!='points_consume') {
					
					die('<script>alert("积分支付必选！");history.back(-1);</script>') ;
				}
				
				//不选支付支付情况
				if (!I('post.payment_code') && !I('post.pd_pay')) {
					die('<script>alert("会员账户金额不足，请选择其他支付方式！");history.back(-1);</script>') ;
				}
				
				//积分支付
				$user_points = $UserInfo ['integral5'] + $UserInfo ['integral1'] + $UserInfo ['integral2'] ;
				if ($user_points<$order_list['points_amount']) {
					die('<script>alert("会员积分数不足，请选择其他支付方式！");history.back(-1);</script>') ;
				}

			
				//预存款支付
				if (I('post.pd_pay')) {
						
				    //线上支付
					if ($order_list['order_amount']>$UserInfo['member_balance']) {
						$pay_money = $order_list['order_amount'] - $UserInfo['member_balance'];
						//站内支付金额
					    $paymoney = $UserInfo['member_balance'] ;
					} else {
						$paymoney = $order_list['order_amount'] ;
					}
					//dump($paymoney);die;	
				} else {
					//线上支付
					$pay_money = $order_list['order_amount'] ;
					//站内支付金额
					$paymoney = 0 ;
				}
				
				$paypoints = $order_list['points_amount'] ;
				$res = 3 ;
			} else if ($pay_code2['payment_code']==='coinpay') {
				
				//增值币支付
				if ($order_list['gold_amount']>$UserInfo['gold_coin']) {
					die('<script>alert("增值币余额不足，请选择其他支付方式！");history.back(-1);</script>') ;
				}
				$paymoney = $order_list['gold_amount'] ;
				 $res = 4 ;
			}

			//纯账户余额
			if (!$pay_money) {
				
				$pay_user = pay_order_in($paymoney, $paypoints, $UserInfo, $res, $order_list) ;
				
				if ($pay_user) {					
					//支付状态更新
					$pay_num2 = payOrder2($order_list['pay_sn']) ;
					//更新订单支付状态
					unset($data);
					$data ['order_state'] =  20 ;
					$data ['payment_time'] =  time() ;
					$data ['pd_amount'] =  $order_list['order_amount'] ;//预存款支付金额
					$order_st = payOrderAll($this->tb_order, I('post.pay_sn'), $data) ;
				} 
				
				if ($order_st) {	
					$this->error('支付成功！','/member/swjydd') ;
				}
				
			} else {
				
				//需要在线支付
				$pay_money = floatval($pay_money) ;
				session('res_pay',$res);
				//支付宝支付
				if (I('post.payment_code')=='alipay') {

					//站内支付方式
					session('online_pay_type','alipay');
				    session('paypoints',$paypoints);
					$this->order_pay_alipay ($pay_money, $paymoney, $order_list) ;
						
				} else {
					die('<script>alert("抱歉！该支付未开放，请先使用其他支付方式！");history.back(-1);</script>') ;
				}	
				
			}
				
		} else {
			die('<script>alert("非法操作！");history.back(-1);</script>') ;
		}
	}

	/**
	*支付宝支付
	*/	
	private function order_pay_alipay ($pay_money, $paymoney, $order_list) {
		if ($order_list) {
			//PHP判断是否通过手机访问可以通过浏览器的UA判断
			if(stripos($_SERVER['HTTP_USER_AGENT'],"android")!=false||stripos($_SERVER['HTTP_USER_AGENT'],"ios")!=false||stripos($_SERVER['HTTP_USER_AGENT'],"wp")!=false){
				//echo '手机访问';
			} else {
				//echo '电脑访问';
				
			}
		
			$Pay = new AlipayController();
			$aa = $Pay->doalipay($pay_money, $paymoney, $order_list);
			
		} else {
			die('<script>alert("订单不存在！");history.back(-1);</script>') ;
		}
	}
	
}